/*
 * @Author: xiaohao
 * @Date: 2025-11-04 17:51:05
 * @LastEditors: xiaohao
 * @LastEditTime: 2025-11-05 21:55:10
 * @FilePath: /Project/ConcurrentMemoryPool/src/ConcurrentAlloc.cpp
 * @Description:
 */
#include "ConcurrentMemoryPool/ConcurrentAlloc.h"
#include "ConcurrentMemoryPool/ThreadCache.h"
#include "ConcurrentMemoryPool/PageCache.h"


void *ConcurrentAlloc(size_t size)
{
    if (size > MAX_BYTES)
    {
        size_t alignSize = SizeClass::RoundUp(size);
        size_t kpage = alignSize >> PAGE_SHIFT;

        PageCache::GetPageCacheInstance()._pageMutex.lock();
        Span *span = PageCache::GetPageCacheInstance().NewSpan(kpage);
        PageCache::GetPageCacheInstance()._pageMutex.unlock();

        void *ptr = (void *)(span->_pageId << PAGE_SHIFT);
        return ptr;
    }
    else
    {
        return ThreadCache::GetThreadInstance().Allocate(size);
    }
}

void ConcurrentFree(void *ptr, size_t size)
{
    if (size > MAX_BYTES)
    {
        Span *span = PageCache::GetPageCacheInstance().MapObjectToSpan(ptr);

        PageCache::GetPageCacheInstance()._pageMutex.lock();
        PageCache::GetPageCacheInstance().ReleaseSpanToPageCache(span);
        PageCache::GetPageCacheInstance()._pageMutex.unlock();
    }
    else
    {
        ThreadCache::GetThreadInstance().Deallocate(ptr, size);
    }
}